/**
 * Created with IntelliJ IDEA.
 * User: ajhin
 * Date: 2/22/14
 * Time: 4:04 PM
 * To change this template use File | Settings | File Templates.
 */
package com.societyGames.utility
{
/**
 * Stores a series of indexed flags.
 * least significant bit is lower index
 *
 **/
public class BitPacker
{
  private var _integers:Vector.<uint> = new Vector.<uint>();
  private static const BITS_PER_INTEGER:int = 32;

  public function getValue(index:uint):Boolean
  {
    var integerIndex:int = int(index / BITS_PER_INTEGER);
    var bitIndex:int = index % BITS_PER_INTEGER;
    if (integerIndex >= _integers.length)
    {
      return false;
    }
    var integer:uint = _integers[integerIndex];
    var mask:uint = 1;
    mask = mask << bitIndex;
    return (integer & mask) != 0;
  }

  public function setValue(index:uint, value:Boolean):void
  {
    var integerIndex:int = int(index / BITS_PER_INTEGER);
    while (integerIndex >= _integers.length)
    {
      _integers.push(0);
    }

    var integer:uint = _integers[integerIndex];
    var bitIndex:int = index % BITS_PER_INTEGER;
    var mask:uint = 1; //0010 //Complement and bitwise |
    mask = mask << bitIndex;
    if (value)
    {
      integer |= (mask);
    }
    else
    {
      integer &= (~mask);
    }
    _integers[integerIndex] = integer;

    for (var cleanIndex:uint = _integers.length - 1; cleanIndex != uint.MAX_VALUE && _integers[cleanIndex] == 0; cleanIndex--)
    {
      _integers.pop();
    }
  }

  public function clear():void
  {
    this._integers.length = 0;
  }

  public function get packedValues():Vector.<uint>
  {
    return _integers;
  }

  public function set packedValues(value:Vector.<uint>):void
  {
    _integers = value;
  }

}
}
